#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <poll.h>

#include "sock.hpp"

using namespace std;

namespace poll_ns
{
    class pollServer
    {
        static const uint16_t gport = 8080;
        static const int num = 2048;
        static const int defaultfd = -1;
        using func_t = function<string (const string&)>;
    public:
        pollServer(func_t f, int port = gport)
            : _port(port), _listensock(-1), _func(f), _rfds(nullptr)
        {
        }
        void Print()
        {
            cout << "fd list:";
            for (int i = 0; i < num; ++i)
            {
                if (_rfds[i].fd != defaultfd)
                    cout << _rfds[i].fd << " ";
            }
            cout << endl;
        }
        void ResetItem(int i)
        {
            _rfds[i].fd = defaultfd;
            _rfds[i].events = 0;
            _rfds[i].revents = 0;
        }
        void initserver()
        {
            _listensock = sock::Socket();
            sock::Bind(_listensock, _port);
            sock::Listen(_listensock);
            _rfds = new struct pollfd[num];

            for (int i = 0; i < num; ++i)
            {
                ResetItem(i);
            }
            
            _rfds[0].fd = _listensock;
            _rfds[0].events = POLLIN;
        }

        void Accepter(int listensock)
        {
            string clientip;
            uint16_t clientport = 0;
            int sock = sock::Accept(listensock, &clientip, &clientport);
            if (sock < 0)
                return;
            else
                logMessage(NORMAL, "accept success [%s, %d]", clientip.c_str(), clientport);

            int i = 0;
            for (; i < num; ++i)
            {
                if (_rfds[i].fd != defaultfd)
                    continue;
                else
                    break;
            }
            if (i == num)
            {
                logMessage(WARNING, "连接满了，添加不上了");
                close(sock);
            }
            else
            {
                _rfds[i].fd = sock;
                _rfds[i].events = POLLIN;
                _rfds[i].revents = 0;
            }
            Print();
        }
        void Recver(int pos)
        {
            char buffer[1024];
            int n = recv(_rfds[pos].fd, &buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                logMessage(NORMAL, "clinet# %s", buffer);
            }
            else if (n == 0)
            {
                close(_rfds[pos].fd);
                ResetItem(pos);
                logMessage(DEBUG, "client quit");
                return ;
            }
            else
            {
                close(_rfds[pos].fd);
                ResetItem(pos);
                logMessage(DEBUG, "client quit");
                return ;
            }

            string responce = _func(buffer);
            write(_rfds[pos].fd, responce.c_str(), responce.size());
        }
        // 在handlerevent rfds中，可能不止一个文件描述符就绪，而是有多个
        void HandlerReadEvent()
        {
            for (int i = 0; i < num; ++i)
            {
                // 过滤掉非法的fd
                if (_rfds[i].fd == defaultfd)
                    continue;
                if (!(POLLIN & _rfds[i].events))
                    continue;
                if (_listensock == _rfds[i].fd && (POLLIN & _rfds[i].revents) )
                {
                    Accepter(_listensock);
                }
                else if(POLLIN & _rfds[i].revents)
                {
                    Recver(i);
                }
            }
        }
        void start()
        {
            int timeout = -1;
            for (;;)
            {
                int n = poll(_rfds, num, timeout);
                switch (n)
                {
                case 0:
                    logMessage(NORMAL, "timeout...");
                    break;
                case -1:
                    logMessage(ERROR, "select error, errcode: %d err describe: %s", errno, strerror(errno));
                    break;
                default:
                    logMessage(NORMAL, "have event ready!");
                    HandlerReadEvent();
                    // break;
                }
            }
        }
        ~pollServer()
        {
            if (_listensock < 0)
                close(_listensock);
            if (_rfds)
                delete[] _rfds;
        }

    private:
        int _port;
        int _listensock;
        struct pollfd* _rfds;
        func_t _func;
    };

}